package com.evan.kdl.test.day02;

import com.evan.kdl.util.CommonUtils;

import java.util.Random;
import java.util.concurrent.CompletableFuture;

/**
 * @author huangzhongliang
 * 异步任务交互指将异步任务获取结果的**速度相比较**，按一定的规则( **先到先用** )进行下一步处理
 * 速记心法：任务1、任务2就像两辆公交，哪路公交先到，就乘坐(使用)哪路公交。
 * @time 2024/01/06 18:02
 */
public class ApplyToEitherDemo {
    public static void main(String[] args) {
        //任务1
        CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
            //到不了3
            int x = new Random().nextInt(2);
            CommonUtils.sleepSecond(x);
            CommonUtils.printThreadLog("任务1耗时:" + x + "秒");
            return x;
        });

        //任务2
        CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
            int y = new Random().nextInt(2);
            CommonUtils.sleepSecond(y);
            CommonUtils.printThreadLog("任务2耗时:" + y + "秒");
            return y;
        });


        CompletableFuture<Integer> future = future1.applyToEither(future2, (result) -> {
            CommonUtils.printThreadLog("最先到达的结果:" + result);
            return result;
        });

        CommonUtils.sleepSecond(3);
        System.out.println("future.join() = " + future.join());

    }
}
